package com.xinongbest.factory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lemonwan
 * 单例对象：获取xml配置的对象
 */
public class BeanFactory {

    private BeanFactory() {

    }

    private static final BeanFactory beanFactory = new BeanFactory();

    private static Map<String, Object> beans = new HashMap<>();

    /**
     * 静态代码块
     */
    static {
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(resourceAsStream);
            Element rootElement = read.getRootElement();
            List<Element> elements = rootElement.selectNodes("//bean");
            for (Element element : elements) {
                String id = element.attributeValue("id");
                String aClass = element.attributeValue("class");
                Object o = Class.forName(aClass).newInstance();
                beans.put(id, o);
            }
            // 解析每一个bean的property属性
            List<Element> list = rootElement.selectNodes("//property");
            for (Element element : list) {
                Element parent = element.getParent();
                String name = element.attributeValue("name");
                String ref = element.attributeValue("ref");
                String id = parent.attributeValue("id");
                Object obj = beans.get(id);
                Method[] methods = obj.getClass().getMethods();
                for (Method method : methods) {
                    if (method.getName().equalsIgnoreCase("set" + name)) {
                        method.invoke(obj, beans.get(ref));
                    }
                }
                beans.put(id, obj);
            }
            resourceAsStream.close();
        } catch (DocumentException | IllegalAccessException | ClassNotFoundException | InstantiationException | IOException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static BeanFactory getInstance() {
        return beanFactory;
    }

    public Object getBean(String id) {
        return beans.get(id);
    }
}
